# -*- coding: utf-8 -*-
# @Time    : 2020/10/29 11:45
# @Author  : YAQIWE
# @File    : ProxyAccess.py
# @Software:  PyCharm
# @explain : 获取通过代理请求

import random
from urllib.parse import urlencode

from bs4 import BeautifulSoup

from util.LogginUtil import logging
from util.RequestUtil import RequestUtil


class ProxyAccess:
    url = 'https://www.kuaidaili.com/free/inha/{}/'

    paramas = {
        'orderid': '970395265553341',
        'num': 1,
        'pt': 1,
        'format': 'json',
        'sep': 1,
        'dedup': 1,
        'area': '4403,4401,4404,4405,4406'
    }
    getIpUrl = 'https://dps.kdlapi.com/api/getdps/'

    def __init__(self):
        self.requestUtil = RequestUtil()
        self.ipList = self.getPayIP()
        self.uploadProxies()

    def getIPList(self, page=1):
        """
        获取免费ip列表
        :param page:
        :return:
        """
        res = self.requestUtil.getRequestThisIp(self.url.format(page))
        bs = BeautifulSoup(res.text.encode('utf8'), 'html.parser')
        items = bs.find_all('tr')
        logging.info('获取ip数：{}'.format(len(items)))
        ipList = []
        for item in items[1:]:
            tdList = item.find_all('td')
            ip = tdList[0].text + ":" + tdList[1].text
            ipList.append(ip)
        return ipList

    code = {'2': '订单已过期', '3': '暂无可用代理', '-1': '订单无效。如果刚下单，请耐心等待一会儿，3分钟内系统会自动发货。',
            '-3': '参数错误', '-4': '提取失败: $err_msg', '-5': '此订单不能提取私密代理。', '-51': '此订单1分钟内允许最多$ip_number个ip调用',
            '-16': '订单已退款', '-15': '订单已过期', '-14': '订单被封禁，请联系客服处理', '-13': '订单已过期',
            '-12': '订单无效', '-11': '订单尚未支付'
            }

    def getPayIP(self, ipNumber=1):
        """
        获取付费ip列表
        :return:
        """
        self.paramas['num'] = ipNumber
        data = urlencode(self.paramas)
        url = self.getIpUrl + '?' + data
        res = self.requestUtil.getRequestThisIp(url)
        if res.status_code == 200:
            info = res.json()
            if info['code'] == 0:
                logging.info('获取ip：{}'.format(info['data']['proxy_list']))
                return info['data']['proxy_list']
            else:
                logging.info('请求错误，code:{}'.format(info['code']))
        return -1

    ipList = []

    def proxiesReq(self, url):
        """
        通过代理ip请求
        :param url:
        :return:
        """
        while True:
            res = self.requestUtil.getRequest(url, self.proxies)
            if -1 != res:
                return res
            else:
                self.ipList = self.getPayIP()
                logging.debug('更新代理ip:{}'.format(self.ipList))
                self.uploadProxies()

    def uploadProxies(self):
        """
        更新代理ip设置
        :return:
        """
        userName = '15338230927'
        password = 'ynbuh4hv'
        self.proxies = {
            "http": "http://{user}:{pwd}@{proxy}/",
            "https": "https://{user}:{pwd}@{proxy}/"
        }.copy()
        self.proxies['http'] = self.proxies['http'].format(user=userName, pwd=password,
                                                 proxy=random.choice(self.ipList))
        self.proxies['https'] = self.proxies['https'].format(user=userName, pwd=password,
                                                   proxy=random.choice(self.ipList))
        logging.debug('代理地址:{}'.format(self.proxies))
        return self.proxies